<?php
/**
 * Created by PhpStorm.
 * Script Name: Client.php
 * Create: 2022/11/1 19:18
 * Description:
 * Author: fudaoji<fdj@kuryun.cn>
 */

namespace app\common\coroutine;

class Client
{
    private static $instance = null;
    private $options = [
        'driver' => 'swoole',
        'host' => '0.0.0.0',
        'port' => 9501,
        'package_max_length'  => 128 * 1024 * 1024
    ];
    private $client;

    public static function instance($options = []){
        if(is_null(self::$instance)){
            self::$instance = new self($options);
        }
        return self::$instance;
    }

    public function __construct($options = [])
    {
        $this->options = array_merge($this->options, $options);
        switch ($this->options['driver']){
            default:
                $this->client = new \swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_SYNC);
                $ret = $this->client->connect($this->options['host'], $this->options['port']);
                if (empty($ret)) {
                    throw new \Exception("连接swoole服务器失败");
                }
                break;
        }
    }

    public function send($params = []){
        return $this->client->send(json_encode($params, JSON_UNESCAPED_UNICODE));
    }
}